package judesart.app.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import judesart.app.domain.Artist;
import judesart.app.domain.Artwork;
import judesart.app.domain.Project;
import judesart.app.domain.User;
import judesart.app.repository.ArtistDAO;
import judesart.app.repository.ArtworkDAO;
import judesart.app.repository.ImageDAO;
import judesart.app.repository.ProjectDAO;
import judesart.app.service.UserService;
import judesart.common.bean.ApplicationContextProvider;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PhotosSaveServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private final static Log LOGGER = LogFactory.getLog(PhotosSaveServlet.class);

    ArtistDAO artistDAO = ApplicationContextProvider.getCtx().getBean(
            ArtistDAO.class);
    ArtworkDAO artworkDAO = ApplicationContextProvider.getCtx().getBean(
            ArtworkDAO.class);
    ProjectDAO projectDAO = ApplicationContextProvider.getCtx().getBean(
            ProjectDAO.class);
    ImageDAO imageDAO = ApplicationContextProvider.getCtx().getBean(
            ImageDAO.class);
    UserService userService = ApplicationContextProvider.getCtx().getBean(
            UserService.class);

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        String result = executeAction(request,
                (List<String>) request.getSession().getAttribute(
                        "JAW-UPLOADED-FILES"));
        request.getSession().removeAttribute("JAW-UPLOADED-FILES");
        request.getSession().removeAttribute("FILES");
        response.getOutputStream().write(result.getBytes());
    }

    @SuppressWarnings("unchecked")
    public String executeAction(HttpServletRequest request,
            List<String> sessionFiles) {
        LOGGER.debug("*********************************************");
        for (String fileItem : sessionFiles) {
            LOGGER.debug(" --> " + fileItem);
        }
        try {
            String action = request.getParameter("action");
            String result = null;
            if (action == null || "addToArtist".equals(action)) {
                result = addToArtist(sessionFiles);
            } else if ("addToArtwork".equals(action)) {
                result = addToArtwork(request.getParameter("id"), sessionFiles);
            } else if ("addToProjectSketch".equals(action)) {
                result = addToProjectSketch(request.getParameter("projectId"),
                        sessionFiles);
            } else if ("addToProjectPhoto".equals(action)) {
                result = addToProjectPhoto(request.getParameter("projectId"),
                        sessionFiles);
            }
            return result;
        } catch (Throwable t) {
            LOGGER.error("Error uploading image", t);
            return null;
        }

    }

    private String addToArtist(java.util.List<String> sessionFiles)
            throws IOException {
        LOGGER.debug("\n\n\n > addToArtist size:[" + sessionFiles.size()
                + "]\n\n\n");
        User user = userService.getCurrentUser();
        if (user != null) {
            Artist artist = artistDAO.findArtistByUserId(user.getId());
            for (String fileItem : sessionFiles) {
                LOGGER.debug("\n\n\n type:[" + fileItem.getClass().getName()
                        + "]\n\n\n");
                artist = artistDAO.addImageToArtist(artist, fileItem, fileItem);
                LOGGER.debug("Image saved");
            }
            return artist.getPhotos().get(artist.getPhotos().size() - 1).getImageId().toString();
        }
        return null;
    }

    private String addToArtwork(String artworkId,
            java.util.List<String> sessionFiles) throws IOException {
        Artwork artwork = artworkDAO.findArtworkById(new Long(artworkId));
        if (artwork != null) {
            for (String fileItem : sessionFiles) {
                artwork = artworkDAO.addImageToArtwork(artwork, fileItem,
                        fileItem);
                LOGGER.debug("Image added to artwork [" + artworkId + "]");
            }
            return artwork.getPhotos().get(artwork.getPhotos().size() - 1).getImageId().toString();
        }
        return null;
    }

    private String addToProjectSketch(String projectId,
            java.util.List<String> sessionFiles) throws IOException {
        Project project = projectDAO.findProjectById(new Long(projectId));
        if (project != null) {
            for (String fileItem : sessionFiles) {
                project = projectDAO.addSketchToProject(project, fileItem,
                        fileItem);
                LOGGER.debug("Image added to project sketch [" + projectId
                        + "]");
            }
        }
        return project.getSketchs().get(project.getSketchs().size() - 1).getImageId().toString();
    }

    private String addToProjectPhoto(String projectId,
            java.util.List<String> sessionFiles) throws IOException {
        Project project = projectDAO.findProjectById(new Long(projectId));
        if (project != null) {
            for (String fileItem : sessionFiles) {
                project = projectDAO.addPhotoToProject(project, fileItem,
                        fileItem);
                LOGGER.debug("Image added to project photo [" + projectId + "]");
            }
        }
        return project.getPhotos().get(project.getPhotos().size() - 1).getImageId().toString();
    }

}
